package com.android.newsreader;

import java.io.IOException;

import android.content.Context;
import android.util.Log;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;


/**
* Class for creating a Db4o database
* 
* Sourced from: 
* 	http://java.dzone.com/articles/using-db4o-android-application
* 
* Modified for RSS classes 
*/
public class Db4oHelper {
	
	private static ObjectContainer mObjContainer = null;
	
	private Context mContext;
	
	/**      
	* @param ctx
	*/
	public Db4oHelper(Context ctx) {
		mContext = ctx;
	}
	
	/**
	* Create, open and close the database
	*/
	public ObjectContainer db() {
	 
		try {
			if (mObjContainer == null || 
					mObjContainer.ext().isClosed()) {
				mObjContainer = Db4oEmbedded.openFile(dbConfig(), db4oDBFullPath(mContext));
	
			}
	
			return mObjContainer;
	 
		} catch (Exception ie) {
			Log.e(Db4oHelper.class.getName(), ie.toString());
	
			return null;
		}
	}
	 
	/**
	* Configure the behavior of the database
	*/
	private EmbeddedConfiguration dbConfig() throws IOException {
	
		EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
		
		configuration.common().objectClass(RSSChannel.class).objectField("mName").indexed(true);
		configuration.common().objectClass(RSSChannel.class).cascadeOnUpdate(true);
		configuration.common().objectClass(RSSChannel.class).cascadeOnActivate(true);
	
		configuration.common().objectClass(RSSItem.class).objectField("mURL").indexed(true);
		configuration.common().objectClass(RSSItem.class).cascadeOnUpdate(true);
		configuration.common().objectClass(RSSItem.class).cascadeOnActivate(true);
		
		return configuration;
	
	}
	
	/**
	* Returns the path for the database location
	*/
	private String db4oDBFullPath(Context ctx) {
		return ctx.getDir("data", 0) + "/" + "pumpup.db4o";
	}
	
	/**
	* Closes the database
	*/
	public void close() {
		
		if (mObjContainer != null)
			mObjContainer.close();
	}
	
}
